<?php
namespace App\Api\Controllers\User;

use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Api\Controllers\Config\HuiPayConfigController;
use App\Api\Controllers\BaseController;
use App\Models\WeixinStore;
use App\Models\CustomerAppletsCoupons;
use App\Models\CustomerAppletsCouponUsers;

class WxCashCouponController extends BaseController
{
    /**
     * 微信代金券列表
     */
    public function wxCashCouponList(Request $request)
    {
        // 接收参数
        $input = $request->all();
        $page = $input['p'] ?? 1;
        $limit = $input['l'] ?? 10;
        $start = abs(($page - 1) * $limit);
        $date = date('Y-m-d H:i:s', time());

        $model = new CustomerAppletsCoupons();
        $list = [];
        $count = $model->getCashCouponCount($input);
        if ($count > 0) {
            $list = $model->getStoreCashCouponPageList($input, $start, $limit);
            foreach ($list as $k => $v) {
                if ($v['coupon_stock_type'] == 'NORMAL') {
                    $list[$k]['coupon_stock_type_name'] = '满减券';
                }
                if ($v['status'] == 1) {
                    $list[$k]['coupon_status'] = '审核中';
                } else if ($v['status'] == 3) {
                    $list[$k]['coupon_status'] = '审核不通过';
                } else {
                    if ($v['available_end_time'] < $date) {
                        $list[$k]['coupon_status'] = '已过期';
                    } else {
                        $list[$k]['coupon_status'] = '运行中';
                    }
                }

                $list[$k]['channel'] = '官方';
                $list[$k]['used_percent'] = ($v['used_num'] / $v['max_coupons']) * 100 . '%';
            }
        }

        return $this->sys_response_layui(1, '请求成功', $list, $count);
    }

    /**
     * 微信代金券批次详情
     */
    public function wxCashCouponStocksDetail(Request $request)
    {
        $input = $request->all();
        $page = $input['p'] ?? 1;
        $limit = $input['l'] ?? 10;
        $start = abs(($page - 1) * $limit);

        // 参数校验
        $checkData = [
            'store_id' => '门店号',
            'stock_id' => '批次号'
        ];
        $check = $this->check_required($input, $checkData);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $customerAppletsCouponUsersModel = new customerappletsCouponUsers();

        // 用户领用代金券数量
        $userCouponCount = $customerAppletsCouponUsersModel->getUserGetCashCouponCount($input);

        $userCouponPageList = [];
        $date_now = date('Y-m-d H:i:s', time());
        if ($userCouponCount > 0) {
            // 获取微信代金券领用、核销分页列表（用户）
            $userCouponPageList = $customerAppletsCouponUsersModel->getUserGetCashCouponPageList($input, $start, $limit);
            foreach ($userCouponPageList as $k => $v) {
                $userCouponPageList[$k]['past_coupon_num'] = 0;
                if ($v['available_end_time'] < $date_now) {
                    $userCouponPageList[$k]['past_num'] += 1;
                }
            }
        }

        return $this->sys_response_layui(1, '请求成功', $userCouponPageList, $userCouponCount);
    }

    /**
     * 微信代金券批次使用、核销数量
     */
    public function wxCashCouponStocksCount(Request $request)
    {
        $input = $request->all();
        // 参数校验
        $checkData = [
            'store_id' => '门店号',
            'stock_id' => '批次号'
        ];
        $check = $this->check_required($input, $checkData);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $customerAppletsCouponsModel = new CustomerAppletsCoupons();

        // 微信代金券领用、核销数量、总数量
        $totalCount = $customerAppletsCouponsModel->getCashCouponDetailCount($input);
        if (!empty($totalCount['max_coupons'])) {
            $totalCount['total_sent_num_percent'] = ($totalCount['total_sent_num'] / $totalCount['max_coupons']) * 100 . '%';
            $totalCount['total_used_num_percent'] = ($totalCount['total_used_num'] / $totalCount['max_coupons']) * 100 . '%';
        }

        return $this->sys_response_layui(1, '请求成功', $totalCount);
    }

    /**
     * 微信代金券核销明细列表
     */
    public function wxCashCouponUsedPageList(Request $request)
    {
        $input = $request->all();
        $page = $input['p'] ?? 1;
        $limit = $input['l'] ?? 10;
        $start = abs(($page - 1) * $limit);

        // 参数校验
        $checkData = [
            'store_id' => '门店号'
        ];
        $check = $this->check_required($input, $checkData);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $model = new customerappletsCouponUsers();
        $weixinStore = new WeixinStore();

        // 查询此门店商户号
        $weixinStoreInfo = $weixinStore->where('store_id', $input['store_id'])->first();
        $input['wx_sub_merchant_id'] = $weixinStoreInfo->wx_sub_merchant_id;

        $count = $model->getCashCouponUsedCount($input);
        $list = [];
        if ($count > 0) {
            $list = $model->getCashCouponUsedPageList($input, $start, $limit);
            foreach ($list as $k => $v) {
                switch ($v['status']) {
                    case 'SENDED':
                        $list[$k]['status_name'] = '可用';
                        break;
                    case 'USED':
                        $list[$k]['status_name'] = '已使用';
                        break;
                    case 'EXPIRED':
                        $list[$k]['status_name'] = '已过期';
                        break;
                    default :
                        break;
                }
            }
        }

        return $this->sys_response_layui(1, '请求成功', $list, $count);
    }

    // 审核微信代金券
    public function checkWechatCoupon(Request $request)
    {
        $requestData = $request->all();

        $id = $requestData['id'];
        $updateData = ['status' => $requestData['status']];

        $model = new CustomerAppletsCoupons();
        $updateRes = $model->updateWechatCoupon($id, $updateData);

        if ($updateRes) {
            return $this->sys_response_layui(1, '操作成功');
        } else {
            return $this->sys_response_layui(2, '操作失败');
        }
    }

    // 删除微信代金券
    public function deleteWechatCoupon(Request $request)
    {
        $requestData = $request->all();
        $id = $requestData['id'];

        $updateData = ['is_delete' => 2];

        $model = new CustomerAppletsCoupons();
        $updateRes = $model->updateWechatCoupon($id, $updateData);

        if ($updateRes) {
            return $this->sys_response_layui(1, '操作成功');
        } else {
            return $this->sys_response_layui(2, '操作失败');
        }
    }

}
